from sqlalchemy import types
from sqlalchemy import orm

import model as m

SA_TYPETOPE = {
    types.Integer: m.Number,
}

def tope_from_saobject(obj, fields=None, **kw):
    '''Create a tope model that reflects a SA model object'''
    mapper = orm.class_mapper(obj)
    if fields is None:
        props = [ p for p in mapper.iterate_properties
                  if isinstance(p, orm.ColumnProperty) ]
    else:
        props = [ mapper.get_property(f) for f in fields ]
    subtopes = [ tope_from_saproperty(p) for p in props ]
    subtope_index = dict((st.name, st) for st in subtopes)
    return m.TopeGroup(obj.__class__.__name__, fields=subtopes)

def tope_from_saproperty(p):
    col = p.columns[0]
    tope = SA_TYPETOPE.get(col.type.__class__, m.StringTope)
    return tope(p.key)
